const getroletypes = async() => {
    try {
        let response = await ajax('getroletypes?pagenum=1&pagesize=30')
        let types = response.data,
            roletype_select = document.querySelector('.roletype')
        for (const type of types) {
            let option = document.createElement('option')
            option.innerHTML = type.roletypename
            option.value = type.id
            roletype_select.add(option)
        }
    } catch (error) {
        alert(error.msg)
    }
}

const getgames = async() => {
    try {
        let response = await ajax('getgames?pagenum=1&pagesize=30')
        let games = response.data
        game_select = document.querySelector('.game')
        for (const game of games) {
            let option = document.createElement('option')
            option.innerHTML = game.gamename
            option.value = game.id
            game_select.add(option)
        }
    } catch (error) {
        alert(error.msg)
    }
}

const role_add = async() => {
    let rolename = document.querySelector('.rolename').value,
        cover = document.querySelector('.cover').value,
        descriotion = document.querySelector('.description').value,
        roletype_select = document.querySelector('.roletype'),
        roletype = roletype_select.options[roletype_select.selectedIndex].value,
        game_select = document.querySelector('.game'),
        game = game_select.options[game_select.selectedIndex].value,
        gender,
        gender_radios = document.querySelectorAll('.gender')
    for (const raido of gender_radios) {
        if (raido.checked) {
            gender = raido.value
        }
    }
    if (!rolename || rolename.trim().length == 0) return alert('角色名称必填');
    if (!roletype || roletype.trim().length == 0) return alert('角色类型必选');
    if (!game || game.trim().length == 0) return alert('所属游戏必选');
    if (!gender || gender.trim().length == 0) return alert('角色性别必选')

    try {
        let obj = {
            rolename,
            cover,
            roletype,
            game,
            gender,
            descriotion
        }
        const response = await ajax('addrole', 'POST', obj)
        alert('添加角色成功')
        location.href = '../roles.html'
    } catch (error) {
        alert(error.meta.msg)
    }
}

window.onload = function() {
    getroletypes()
    getgames()
}